/*
 * BanBu_SmileLabelCell
 * @description 本文件提供聊天界面对话界面显示纯文字消息的cell
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供聊天界面对话界面显示纯文字消息的cell
 */

#import "BanBu_SmileLabelCell.h"
#import "BanBuAPIs.h"
#import "AppDataManager.h"

@implementation BanBu_SmileLabelCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        _smileLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        
        _smileLabel.numberOfLines = 0;
        _smileLabel.backgroundColor = [UIColor clearColor];
        _smileLabel.tag = 101;
        [self addSubview:_smileLabel];
        
        //锁图片
        _lockImage = [[UIImageView alloc]initWithFrame:CGRectZero];
        _lockImage.backgroundColor = [UIColor clearColor];
        _lockImage.image = [UIImage imageNamed:@"lock_Image.png"];
        _lockImage.hidden = YES;
        [self addSubview:_lockImage];
        
        //阅后即焚消息
        _backgroundTime = [[UIImageView alloc]initWithFrame:CGRectZero];
        _backgroundTime.backgroundColor = [UIColor clearColor];
        _backgroundTime.image = [UIImage imageNamed:@"sexangle_black.png"];
        _backgroundTime.hidden = YES;
        [self addSubview:_backgroundTime];
        
        _snapTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.bkView.frame.origin.x+5, self.bkView.frame.origin.y-2, 20, 20)] ;
        _snapTimeLabel.font = [UIFont systemFontOfSize:12];
        _snapTimeLabel.textColor = [UIColor whiteColor];
        _snapTimeLabel.backgroundColor = [UIColor clearColor];
        _snapTimeLabel.textAlignment = UITextAlignmentCenter;
        _snapTimeLabel.hidden = YES;
        [self addSubview:_snapTimeLabel];

    }
    return self;
}

-(void)dealloc
{
    [_lockImage release],_lockImage = nil;
    [_backgroundTime release],_backgroundTime = nil;
    [_snapTimeLabel release],_snapTimeLabel = nil;
    [_smileLabel release],_smileLabel = nil;
    [_smileSnapLabel release],_smileSnapLabel = nil;
    [super dealloc];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    switch (self.bubbleID)
    {
        case 0:
            _smileLabel.frame = SmileLabelRect00;
            break;
        case 9:
            _smileLabel.frame = SmileLabelRect02;
            break;
        default:
            _smileLabel.frame = SmileLabelRect01;
            break;
    }
    
    float height = self.contentView.frame.size.height;
    
    if ([self.from isEqualToString:@"snap"])
    {
        if (self.atLeft)
        {
            //阅后即焚,接到的消息显示为悄悄话；自己发的消息显示为实际消息内容
            if (self.smileSnapLabel.length == 0)//长按后
            {
                height = self.height;
                _snapTimeLabel.textColor = [UIColor whiteColor];
                
                self.bkView.frame = BKViewRect03(self.bkViewWidth, height);
                
                _smileLabel.frame = SmileLabelRect00;
                _lockImage.hidden = YES;
                _backgroundTime.hidden = NO;
                
                CGRect frame = self.bkView.frame;
                _snapTimeLabel.frame = CGRectMake(frame.origin.x+frame.size.width+5, frame.origin.y-2, 20, 20);
                _backgroundTime.frame = CGRectMake(frame.origin.x+frame.size.width+5, frame.origin.y-2, 20, 20);
                [self performSelector:@selector(countdownCounter:) withObject:nil afterDelay:1];
            }
            else
            {
                _lockImage.hidden = NO;
                if (self.showTime)
                {
                    height = 84;
                }
                else
                {
                    height = 60;
                }
                self.bkView.frame = BKViewRect00(self.bkViewWidth, height);
                _smileLabel.frame = SmileLabelRect00;
                _backgroundTime.hidden = YES;
                
                CGRect frame = self.bkView.frame;
                _lockImage.frame = CGRectMake(frame.origin.x+frame.size.width-15, frame.origin.y, 15, 15);
            }
        }
        else
        {
            _lockImage.hidden = NO;
            _backgroundTime.hidden = YES;
            _snapTimeLabel.textColor = [UIColor blackColor];
            
            CGRect frame = self.bkView.frame;
            _lockImage.frame = CGRectMake(frame.origin.x, frame.origin.y, 15, 15);
            _snapTimeLabel.frame = CGRectMake(frame.origin.x+5, frame.origin.y-2, 20, 20);
        }
    }
    else
    {
        _snapTimeLabel.hidden = YES;
        _backgroundTime.hidden = YES;
        _lockImage.hidden = YES;
    }
    
//    if (self.bubbleID == 0)
    {
        CGRect frame = _smileLabel.frame;
        frame.origin.y += 4;
        if (!self.atLeft)
        {
            frame.origin.x += 3;
        }
        _smileLabel.frame = frame;
    }

    //如果显示from
    if (self.showFrom)
    {
        [self setShowFromFrame:ChatMsgSmileLabel];
    }
    
    self.avatar.frame = AvatarRect01;
//    [self.vipImageView setFrame:CGRectMake(self.avatar.frame.origin.x + 28, self.avatar.frame.origin.y + 26, 15, 10)];
}

//设置文本型消息的内容
- (void)setSmileLabelText:(NSString *)text
{
    self.smileLabel.text = text;
    
   CGSize size =  [self.smileLabel.text sizeWithFont:DefaultFont constrainedToSize:CGSizeMake(MaxWidth-20, 1000)lineBreakMode:kTextLineBreakByWordWrapping];
    
    NSLog(@"size:%@",NSStringFromCGSize(size));
    if (size.width<23)
    {
        size.width = 23;
    }

    CGRect newFrame = self.smileLabel.frame;
    newFrame.size.height = size.height + ((size.height>20 )?20:0)+30;
    newFrame.size.width = (size.height>DefaultHeight)?MaxWidth:(size.width + 20);
    
    self.smileLabel.frame = newFrame;
    self.bkViewWidth = self.smileLabel.frame.size.width;
    
    if(self.smileLabel.frame.size.width>180)
    {
        self.bkViewWidth = 180;
    }
}

//文本的高度（type：text）
+(float)heightForText:(NSString *)text
{
    NSArray *smiles = [SmileStr componentsSeparatedByString:@"|"];
    for(NSString *aSmile in smiles)
    {
        text = [text stringByReplacingOccurrencesOfString:aSmile withString:@"ww"];
    }
    
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(260-20, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
    
    return size.height;
}

//设置cell的各种信息
-(void)setChatCellInfo:(NSDictionary *)amsg
{
    //设置父类的属性
    [super setChatCellInfo:amsg];
    
    if ([self.from isEqualToString:@"snap"])
    {
        if (self.atLeft)
        {
            if ([[amsg valueForKey:@"changanhou"] boolValue])
            {
                [self setSmileLabelText:[amsg valueForKey:KeyContent]];
                self.smileSnapLabel = nil;
            }
            else
            {
                NSString * str = NSLocalizedString(@"longPressToSee", nil);
                
                [self setSmileLabelText:str];
                self.smileSnapLabel = [amsg valueForKey:KeyContent];
            }
        }
        else
        {
            self.lockImage.hidden = NO;
            self.backgroundTime.hidden = YES;
            _snapTimeLabel.textColor = [UIColor blackColor];
            
            [self setSmileLabelText:[amsg valueForKey:KeyContent]];
            self.smileSnapLabel = nil;
        }
        _effectiveTime = [[amsg valueForKey:KeyEffectiveTime] integerValue];
    }
    else
    {
        [self setSmileLabelText:[amsg valueForKey:KeyContent]];
        self.smileSnapLabel = nil;
    }
}

//阅后即焚：文本型；倒计时
//倒计时
-(void)countdownCounter:(NSInteger)effectiveTime
{
    if (!self.snapTimeLabel.hidden)
    {
        return;
    }
    effectiveTime  = self.effectiveTime;
    if (effectiveTime == 0)
    {
        effectiveTime = 3;
    }
    _smileSnapLabel = nil;
    
    if (self.atLeft)
    {
        if (effectiveTime>2)
        {
            _backgroundTime.image = [UIImage imageNamed:@"sexangle_black.png"];
        }
        else
        {
            _backgroundTime.image = [UIImage imageNamed:@"sexangle_red.png"];
        }
        _backgroundTime.hidden = NO;
        _snapTimeLabel.textColor = [UIColor whiteColor];
    }
    
    __block int timeout = effectiveTime; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    _snapTimeLabel.hidden = NO;
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0)//倒计时结束，关闭
        {
            dispatch_source_cancel(_timer);
            dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                self.snapTimeLabel.textColor = [UIColor blackColor];
                self.snapTimeLabel.hidden = YES;
                self.backgroundTime.hidden = YES;
                _backgroundTime.image = [UIImage imageNamed:@"sexangle_black.png"];
                
                NSMutableDictionary * amsg = [NSMutableDictionary dictionaryWithCapacity:3];
                [amsg setValue:self.userid forKey:KeyFromUid];
                [amsg setValue:self.chatid forKey:KeyChatid];
                [amsg setValue:_smileLabel.text forKey:KeyContent];
                
                [MyAppDataManager deleteOneChattingRecordOfOnePerson:amsg];
                [MyAppDataManager deleteTalkRecordOfOnePerson:amsg];
                
                //刷新界面
                if (MyAppDataManager.chatuid && [MyAppDataManager.chatuid isEqualToString:self.userid])
                {
                    [MyAppDataManager.appChatController removeRow:self];
                }
            });
        }
        else
        {
            NSString *strTime = [NSString stringWithFormat:@"%d",timeout];
            NSInteger time = timeout;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                if(MyAppDataManager.appChatController == nil)
                {
                    MyAppDataManager.chatuid = nil;
                    timeout = 0;
                }
                if (time<=3)
                {
                    if (!self.atLeft)
                    {
                        _snapTimeLabel.textColor = [UIColor redColor];
                    }
                    else
                    {
                        _backgroundTime.image = [UIImage imageNamed:@"sexangle_red.png"];
                    }
                }
                self.snapTimeLabel.text = strTime;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

-(void)remove
{
    if ([self.delegate respondsToSelector:@selector(removeRow:)])
    {
        [self.delegate removeRow:self];
    }
}

@end
